package com.tidc.seaserverweb;

import com.tidc.seaservermapper.dao.RabbitMessageLogDao;
import com.tidc.seaservermodel.config.RabbitConstants;
import com.tidc.seaservermodel.entity.RabbitMessageLog;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.Order;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;
import java.util.Arrays;

@SpringBootApplication
@MapperScan(basePackages = "com.tidc.seaservermapper")
@ComponentScan(value="com.tidc")
@EnableTransactionManagement
@Slf4j
public class SeaServerWebApplication {
    @Resource
    private RabbitMessageLogDao rabbitMessageLogDao;
    @Resource
    private CachingConnectionFactory cachingConnectionFactory;
    //TODO 可以给Supervisor一个失约统计 文件上传没写
    public static void main(String[] args) {
        SpringApplication.run(SeaServerWebApplication.class, args);
    }
    @Bean
    @Order(999)
    RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
//		设置消息发送的回调
        rabbitTemplate.setConfirmCallback((data, ack, cause) -> {
            if (ack) {
                RabbitMessageLog rabbitMessageLog = rabbitMessageLogDao.queryByMsgId(data.getId());
                log.info(rabbitMessageLog + ":消息发送成功");
                rabbitMessageLogDao.updateLogStatus(RabbitConstants.SUCCESS,rabbitMessageLog.getMsgId());
            } else {
                log.info(data.getId() + ":消息发送失败");

            }
        });
//		消息发送失败: 1.直接失败 2.消息从交换机发送到队列失败
        rabbitTemplate.setReturnCallback((msg, repCode, repText, exchange, routingkey) -> {
            log.info("消息发送失败");
        });
        return rabbitTemplate;
    }
    @Bean
    public CorsConfigurationSource corsConfigurationSource(){
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(300L);
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }



}
